﻿using System.Data;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;

namespace Yamfinder.Data
{
    public class UserRepository : IUserRepository
    {
        private readonly MongoCollection<User> _collection;
        public const string CollectionName = "Users";

        public UserRepository(IDataSource dataSource)
        {
            _collection = dataSource.GetCollection<User>(CollectionName);
        }

        public IQueryable<User> Query()
        {
            return _collection.AsQueryable();
        }

        public User Get(ObjectId id)
        {
            return _collection.FindOneById(id);
        }

        public User Get(string username)
        {
            return _collection.FindOne(MatchUsername(username));
        }

        public void Insert(User user)
        {
            //Check for duplicates
            if (_collection.Find(MatchUsername(user.Username)).Count() > 0)
                throw new DataException("Duplicate Username, cannot continue.");

            _collection.Insert(user);
        }

        public void Save(User user)
        {
            var origObject = Get(user.Id);
            if (origObject.Username != user.Username)
            {
                //Check for duplicates
                if (_collection.Find(MatchUsername(user.Username)).Count() > 0)
                    throw new DataException("Duplicate Username, cannot continue.");
            }

            _collection.Save(user);
        }

        public void Remove(ObjectId id)
        {
            _collection.Remove(MatchId(id));
        }

        public void Remove(string username)
        {
            _collection.Remove(MatchUsername(username));
        }

        private QueryComplete MatchId(ObjectId id)
        {
            return MongoDB.Driver.Builders.Query.EQ("_id", id);
        }

        private QueryComplete MatchUsername(string username)
        {
            return MongoDB.Driver.Builders.Query.EQ("Username", username);
        }
    }
}